from src.util.Route import app_error, app_before, app_after, getUsername, getUserRemoteAddr
from flask import request, Response, json
from src.service import LogManageService, AuthService
from src.common.R import R
from src.util.ProcessUtil import pool

# 静态资源前缀
_static_start_url = "/static"


@app_error(404)
def notFound(e: Exception):
    return R.not_found(request.path), 404


@app_before
def interceptor():
    if request.path.startswith(_static_start_url):
        r = AuthService.staticAuth(request)
        if r:
            return
        return R.reject("你无权访问资源" + request.path)
    else:
        r = AuthService.interfaceAuth(request)
        if r:
            return
        if r is None:
            return R.create(303, None, "用户登陆信息已过期请重新登录")
        if not r:
            return R.reject("你无权访问接口" + request.path)


# 记录接口日志
def addInterfaceLog(res: Response):
    path = request.path
    status = res.status_code
    # 如果不在排除列表中，执行特定的操作
    token = request.headers.get("Authorization")
    ip = getUserRemoteAddr()
    username = getUsername()
    if username is None:
        try:
            username = json.loads(request.data)
            username = username.get('username')
        except:
            username = 0
    resp = res.json  # 获取响应数据，并指定为文本
    if resp is None:
        resp = {}
    body = None
    try:
        request.get_data().decode('utf-8')
    except:
        body = {}
    req = {
        "body": body,
        "param": request.args.to_dict()
    }
    pool.submit(LogManageService.addLog, username, token, resp, status, ip, path, req, request.method)


# 记录静态资源日志
def addStaticLog(res: Response):
    pass


@app_after
def after_request_handler(res: Response):
    # 定义默认的值
    path = request.path
    if path.startswith(_static_start_url):
        addStaticLog(res)
        return res
    else:
        addInterfaceLog(res)
        return res  # 注意：必须返回响应对象，以便继续将其发送给客户端
